<?php

use App\Jobs\ProcessImageGenerate;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Route;
use Illuminate\Http\Request;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::post('/submits', function (Request $request) {
    $submits = $request->input('submits', []);
    $names = [];
    foreach ($submits as $submit) {
        $prompt = trim($submit['prompt']);
        $width = intval($submit['width']);
        $height = intval($submit['height']);
        $width = min(1024, max(512, $width));
        $height = min(1024, max(512, $height));
        $steps = intval($submit['steps']);
        $steps = min(50, max(1, $steps));
        $seed = intval($submit['seed']);
        $norwkv = intval($submit['norwkv']);

        if ($seed < 1) {
            $seed = mt_rand(1, 99999999);
        }
        $name = date('Ymd-His').'-'.mt_rand(10000000,99999999);
        ProcessImageGenerate::dispatch($name, $prompt, $width, $height, $steps, $seed, $norwkv);
        $names[] = $name;
    }

    $userFiles = [];
    if (Session::has('images')) {
        $userFiles = Session::get('images');
    }

    // Due to historical reasons, the file name may or may not have an extension
    $userFiles = array_map(function ($f) {
        return pathinfo($f, PATHINFO_FILENAME);
    }, $userFiles);

    Session::put('images', array_merge($userFiles, $names));

    return response(['status' => 0, 'fileNames' => $names], 200)->header('Content-Type', 'application/json');
})->withoutMiddleware([App\Http\Middleware\VerifyCsrfToken::class]); // 关闭CSRF认证

Route::get('/get-images-and-queue-info', function () {
    function FakePhotosListImages(): array
    {
        $userFiles = [];
        if (Session::has('images')) {
            $userFiles = Session::get('images');
        }

        // Due to historical reasons, the file name may or may not have an extension
        $userFiles = array_map(function ($f) {
            return pathinfo($f, PATHINFO_FILENAME);
        }, $userFiles);

        $imageSaveDir = Config::get('images.dir');

        $images = [];
        foreach ($userFiles as $f) {
            if (is_file("$imageSaveDir/{$f}.png")) {
                $images[] = $f;
            }
        }
        return $images;
    }

    function FakePhotosQueueInfo(): string
    {
        $res = proc_open(
            [Config::get('command.php'),Config::get('command.artisan'),'queue:monitor','--no-ansi','--no-interaction','default'],
            [['pipe', 'r'], ['pipe', 'wb'], ['pipe', 'wb']],
            $pipes
        );
        $info = '';
        if (is_resource($res)) {
            do {
                $status = proc_get_status($res);
                if ($status['running']) {
                    usleep(1000);
                }
            } while ($status['running']);
            if (isset($pipes) && is_array($pipes) && isset($pipes[1])) {
                $info = fread($pipes[1], 4096);
            }
            @proc_close($res);
        }
        return $info;
    }

    return response(['status' => 0, 'info' => [
        'images' => FakePhotosListImages(),
        'queueInfo' => FakePhotosQueueInfo(),
    ]], 200)->header('Content-Type', 'application/json');
});
